#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QTextStream>
#include <QDir>
namespace py = pybind11;


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::load_log()
{
    ui->listWidget_log->addItem(" qd");
}

void MainWindow::log(const std::string msg)
{
//    QString path = __FILE__;
//    QString file = path.section("\\", 2, 2);
//    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
//    QString totalmsg = "[" + file + ":" + QString::number(__LINE__)  + " " + time + "] ";
//    totalmsg += msg.c_str();
//    qDebug() << totalmsg;

//    QFile logfile;
//    logfile.setFileName(QString("%1_log.txt").arg(QDateTime::currentDateTime().toString("yyyyMMdd")));
//    if(logfile.open(QIODevice::Append | QIODevice::Text)) {
//        QTextStream(&file) << totalmsg << "\n";
//    }
//    logfile.write(totalmsg.toUtf8());
//    logfile.flush();
//    logfile.close();

    QMetaObject::invokeMethod(qApp, [msg]() {
            QString path = __FILE__;
            QString file = path.section("\\", -1);  // 获取文件名
            QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            QString totalmsg = QString("[%1:%2 %3] %4")
                              .arg(file)
                              .arg(__LINE__)
                              .arg(time)
                              .arg(QString::fromStdString(msg));

            // 打印到控制台
            qDebug() << totalmsg;

            // 写入文件（使用绝对路径）
            QDir dir(QCoreApplication::applicationDirPath());
            QString filename = dir.filePath(QDateTime::currentDateTime().toString("yyyyMMdd") + "_log.txt");

            QFile logfile(filename);
            if(logfile.open(QIODevice::Append | QIODevice::Text)) {
                QTextStream stream(&logfile);
                stream << totalmsg << "\n";
                logfile.close();
            }
        });
}

void MainWindow::on_pushButton_clicked()
{
    qDebug() << "触发该按键，执行python脚本";
    // 初始化Python解释器
        py::scoped_interpreter guard{};

        // 加载我们的绑定模块
        try {
            py::module::import("embedded_logger");
            /*py::exec(R"(
                     import embedded_logger
                     embedded_logger.log("111111")
                 )");*/
            std::ifstream t("D:\\kindsOfProject\\Qtcode\\2025_6_27_pybind\\log_test.py");
            std::string code((std::istreambuf_iterator<char>(t)),
                             std::istreambuf_iterator<char>());
            py::exec(code);
            //py::module_ runpy = py::module_::import("runpy");
            //runpy.attr("run_path")("D:\\kindsOfProject\\Qtcode\\2025_6_27_pybind\\log_test.py");
            //runpy.attr("run_path")("log_test.py");
        } catch (py::error_already_set &e) {
            qCritical() << "Python error:\n" << e.what();
        }
}

void MainWindow::on_pushButton_2_clicked()
{
    qDebug() << "okokok";
}

void execute_file_with_exec(const std::string& filename) {
    py::scoped_interpreter guard{};
    std::ifstream t(filename);
    std::string code((std::istreambuf_iterator<char>(t)),
                     std::istreambuf_iterator<char>());


    // 关键：注入__file__变量使相对路径生效
//    py::dict scope;
//    scope["__file__"] = filename;

    py::exec(code);
}
